﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace SoIM.Client
{
    public partial class frmReceive : Form
    {
        UdpClient udpClient;   //定义UDPClient对象
        Thread t;      //定义线程，用于启动接收消息方法
        public frmReceive()
        {
            InitializeComponent();

            //加入本句代码，可简单解决跨线程操作控件的错误
            CheckForIllegalCrossThreadCalls = false;
        }

        private void frmReceive_Load(object sender, EventArgs e)
        {
            try
            {
                //实例化UDPClient对象，并绑定本机端口
                udpClient = new UdpClient(int.Parse(txtLocalPort.Text));

                //启动独立线程，用于接收消息
                t = new Thread(ReceiveData);
                //设为后台线程
                t.IsBackground = true;
                //启动线程
                t.Start();
            }
            catch
            {
                MessageBox.Show("端口已被占用！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void txtRemotePort_KeyPress(object sender, KeyPressEventArgs e)
        {
            //控制远程端口文本框的输入内容，只能输入数字。同时启用让删除键（退格键生效）
            if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8)
            {
                e.Handled = true;
            }
        }

        //发送消息
        private void btnSend_Click(object sender, EventArgs e)
        {
            //判断是否输入昵称
            if (txtNick.Text != string.Empty)
            {
                //判断是否输入要发送的消息内容
                if (txtSend.Text != string.Empty)
                {
                    try
                    {
                        //定义远程主机的IP和端口号
                        IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(txtIP.Text), int.Parse(txtRemotePort.Text));

                        //将要发送的消息内容转换成Byte数组
                        byte[] SendByte = Encoding.Unicode.GetBytes(txtNick.Text + "说：" + txtSend.Text + "  (时间:" + DateTime.Now.ToShortTimeString() + ")");

                        //发送Byte数组
                        udpClient.Send(SendByte, SendByte.Length, remoteEndPoint);

                        //添加聊天记录
                        lstRecord.Items.Add(txtNick.Text + "说：" + txtSend.Text + "  (时间:" + DateTime.Now.ToShortTimeString() + ")");

                        //清空消息框
                        txtSend.Text = string.Empty;

                        //状态栏显示发送状态
                        toolMessage.Text = "消息发送成功！";
                    }
                    catch (Exception ex)
                    {
                        toolMessage.Text = ex.ToString();
                    }
                }
                else
                {
                    toolMessage.Text = "请输入要发送的消息！";
                }
            }
            else
            {
                toolMessage.Text = "请先输入您的大名！";
            }
        }
        //接收消息函数 void ReceiveData() { //无限循环 while (true) { try { //接收来自任意IP地址和任意端口的数据 IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 0); //接收数据，并保存到Byte数组里 byte[]

        //接收消息函数
        void ReceiveData()
        {
            //无限循环
            while (true)
            {
                try
                {
                    //接收来自任意IP地址和任意端口的数据
                    IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 0);
                    //接收数据，并保存到Byte数组里
                    byte[] ReceiveByte = udpClient.Receive(ref ipEnd);
                    //将Byte数组解析成字符串并添加到历史记录列表
                    lstRecord.Items.Add(Encoding.Unicode.GetString(ReceiveByte));
                    //提示有新消息到达
                    toolMessage.Text = "有新消息，请注意查收！";
                }
                catch (Exception ex)
                {
                    toolMessage.Text = ex.ToString();
                }
            }
        }

    }
}
